package wyp.library.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

public class WypHttpUtils {

	public static final String TAG = WypHttpUtils.class.getSimpleName();
	private static CookieStore cookieStore;
	public static String JSESSIONID = null;

	public static String sendPostMethod(String __path, Map<String, Object> params, String encoding) throws ClientProtocolException, IOException {
		String __result = null;
		List<NameValuePair> __parameters = new ArrayList<NameValuePair>();
		for (Map.Entry<String, Object> __entry : params.entrySet()) {

			BasicNameValuePair __pair = new BasicNameValuePair(__entry.getKey(), __entry.getValue().toString());
			__parameters.add(__pair);
		}
		UrlEncodedFormEntity __fromEntity = null;
		DefaultHttpClient __client = null;
		try {
			__fromEntity = new UrlEncodedFormEntity(__parameters, encoding);
			__client = new DefaultHttpClient();
			HttpPost __post = new HttpPost(__path);
			if (null != JSESSIONID) {
				__post.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
			}
			__post.setEntity(__fromEntity);
			HttpConnectionParams.setConnectionTimeout(__client.getParams(), 30 * 1000);
			HttpResponse _response = __client.execute(__post);
			if (_response.getStatusLine().getStatusCode() == 200) {
				__result = EntityUtils.toString(_response.getEntity(), encoding);
			}
			cookieStore = __client.getCookieStore();
			List<Cookie> __cookieList = cookieStore.getCookies();
			for (int i = 0; i < __cookieList.size(); i++) {
				if ("JSESSIONID".equalsIgnoreCase(__cookieList.get(i).getName())) {
					JSESSIONID = __cookieList.get(i).getValue();
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} finally {
			if (__client != null) {
				__client.getConnectionManager().shutdown();
			}
		}
		return __result;
	}
}
